package com.warrantyhotel.android.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;

import com.warrantyhotel.android.db.WarrantyHotelDBSchema;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.News_RSS;

public class NewsWarrantyProcessor {

	public static final String RSS = "https://" + HttpConnector.BASE_URL + "/rss.svc/GetNews?format=rss";

	public void processInternal(final ContentResolver resolver) throws IOException, HttpException, Exception {
		InputStream in = null;
		ArrayList<String> remainsListRSS;
		try {
			remainsListRSS = new ArrayList<String>();

			URL privateUrl = new URL(RSS);
			in = privateUrl.openStream();

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();
			xpp.setInput(in, "ISO-8859-1");

			ContentValues values = new ContentValues();
			int eventType = xpp.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("item")) {
					values.clear();
				} else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("guid")) {
					eventType = xpp.next();
					values.put(News_RSS.GUID, xpp.getText());
					remainsListRSS.add(xpp.getText());
				} else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("link")) {
					String title = xpp.getAttributeValue(null, "title");
					if (title != null && title.equals("Thumbnail"))
						values.put(News_RSS.LINK_THUMBNAIL, xpp.getAttributeValue(null, "href"));
					else if (title != null && title.equals("Banner"))
						values.put(News_RSS.LINK_BANNER, xpp.getAttributeValue(null, "href"));
					else {
						eventType = xpp.next();
						values.put(News_RSS.LINK, xpp.getText());
					}
				} else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("title")) {
					eventType = xpp.next();
					values.put(News_RSS.TITLE, xpp.getText());
				} else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("description")) {
					eventType = xpp.next();
					values.put(News_RSS.DESCRIPTION, xpp.getText());
				} else if (eventType == XmlPullParser.START_TAG && xpp.getName().equals("updated")) {
					eventType = xpp.next();
					values.put(News_RSS.DATE_UPDATE, xpp.getText());
				} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equals("item")) {
					resolver.insert(News_RSS.CONTENT_URI, values);
				}
				eventType = xpp.next();
			}
		} finally {
			IOUtil.closeQuietly(in);
		}

		String[] remains = remainsListRSS.toArray(new String[remainsListRSS.size()]);

		ArrayList<ContentProviderOperation> deleteRemains = new ArrayList<ContentProviderOperation>();
		if (remains.length > 0) {
			deleteRemains.add(ContentProviderOperation.newDelete(News_RSS.CONTENT_URI)
					.withSelection(News_RSS.GUID + " not in (" + getPlaceHolder(remains) + ")", remains).build());
			resolver.applyBatch(WarrantyHotelDBSchema.CONTENT_AUTHORITY, deleteRemains);
		} else if (remains.length == 0) {
			resolver.delete(News_RSS.CONTENT_URI, null, null);
		}
	}

	/**
	 * Creation String such as "?,?,?,?,?,?"
	 */

	private String getPlaceHolder(String[] remains) {
		StringBuilder placeHolder = new StringBuilder();

		for (int i = 0; i < remains.length; i++) {
			placeHolder.append("?,");
		}
		// remove last comma
		placeHolder.setLength(placeHolder.length() - 1);
		return placeHolder.toString();
	}

}
